package com.hoperun.checkcloth.activity;

import android.app.DatePickerDialog;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.hoperun.checkcloth.R;
import com.hoperun.checkcloth.base.MIP_BaseActivity;
import com.hoperun.checkcloth.entity.JyChejianModel;
import com.hoperun.checkcloth.net.IServiceImpl;
import com.hoperun.checkcloth.net.RequestServiceImpl;
import com.hoperun.checkcloth.ui.dialog.SimpleDialog;
import com.hoperun.checkcloth.util.MIP_SystemUtils;
import com.hoperun.checkcloth.util.ParseUtils;
import com.hoperun.checkcloth.util.SharedPreUtil;

import org.json.JSONArray;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

public class JyChejianActivity extends MIP_BaseActivity implements View.OnClickListener {
    RecyclerView recylistview;
    TextView usertextview,input_dateTv;
    LinearLayout input_dateLl;
    EditText editbizno;
    QuickAdapter quickAdapter;
    List<JyChejianModel> jychejianlist = new ArrayList<JyChejianModel>();
    List<JyChejianModel> savelist = new ArrayList<JyChejianModel>();
    List<JyChejianModel> deletelist = new ArrayList<JyChejianModel>();
    //日期
    String mJobDate;
    String empID;
    String type;
    private SimpleDateFormat dateFormat_CHINA = new SimpleDateFormat("yyyy年MM月dd日");
    private SimpleDateFormat dateFormat_EN = new SimpleDateFormat("yyyy-MM-dd");
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_jy_chejian);

        recylistview=(RecyclerView)this.findViewById(R.id.recylistview);
        usertextview=(TextView)this.findViewById(R.id.usertextview);
        input_dateTv=(TextView)this.findViewById(R.id.input_dateTv);
        input_dateLl=(LinearLayout)this.findViewById(R.id.input_dateLl);
        editbizno=(EditText)this.findViewById(R.id.editbizno);
        this.findViewById(R.id.deleteBtn).setOnClickListener(this);
        this.findViewById(R.id.shureBtn).setOnClickListener(this);
        this.findViewById(R.id.queryBtn).setOnClickListener(this);
        this.findViewById(R.id.input_dateLl).setOnClickListener(this);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recylistview.setLayoutManager(layoutManager);
        //给RecyclerView设置适配器
        quickAdapter = new QuickAdapter();
        recylistview.setAdapter(quickAdapter);
        recylistview.setHasFixedSize(true);
        recylistview.setNestedScrollingEnabled(false);
        RequestServiceImpl.jy_getsysdate(mMIPHandler, IServiceImpl.JY_GETTIME);

        empID = (String) SharedPreUtil.getValue(this,
                SharedPreUtil.YHBH, "");
        usertextview.setText("检验工："+empID);

        editbizno.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (event != null
                        && event.getKeyCode() == KeyEvent.KEYCODE_ENTER
                        && event.getAction() == KeyEvent.ACTION_UP) {

                    String monadNo = editbizno.getText().toString().trim();
                    if (monadNo.length() >= 4) {

                        querysanlian(monadNo);
                    } else {
                        showSimpleDialog(getResources().getString(R.string.monadno_not_right));
                    }
                    return true;
                }
                return false;
            }
        });
    }

    public class QuickAdapter extends BaseQuickAdapter<JyChejianModel, BaseViewHolder> {
        public QuickAdapter() {
            super(R.layout.item_jychejian, jychejianlist);
        }

        @Override
        protected BaseViewHolder createBaseViewHolder(View view) {
            return super.createBaseViewHolder(view);
        }

        @Override
        protected void convert(BaseViewHolder holder, final JyChejianModel item) {
            TextView item_sanlian = holder.getView(R.id.item_sanlian);
            TextView  item_buhao= holder.getView(R.id.item_buhao);
            CheckBox item_checkBoxhl = holder.getView(R.id.item_checkBoxhl);
            CheckBox item_checkBoxxl = holder.getView(R.id.item_checkBoxxl);
            CheckBox item_checkBoxcz = holder.getView(R.id.item_checkBoxcz);
            CheckBox item_checkBoxyj = holder.getView(R.id.item_checkBoxyj);
            EditText item_beizhu= holder.getView(R.id.item_beizhu);

            CheckBox item_checkBox = holder.getView(R.id.item_checkBox);

            item_checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    jychejianlist.get(holder.getLayoutPosition()).setBoxcheck(isChecked);
                }
            });
            item_checkBoxhl.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                     if(isChecked){
                         jychejianlist.get(holder.getLayoutPosition()).setTRANLOAD("1");
                     }else{
                         jychejianlist.get(holder.getLayoutPosition()).setTRANLOAD("0");
                     }
                }
            });
            item_checkBoxxl.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    if(isChecked){
                        jychejianlist.get(holder.getLayoutPosition()).setGRIN("1");
                    }else{
                        jychejianlist.get(holder.getLayoutPosition()).setGRIN("0");
                    }
                }
            });

            item_checkBoxcz.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    if(isChecked){
                        jychejianlist.get(holder.getLayoutPosition()).setDNEEDLE("1");
                    }else{
                        jychejianlist.get(holder.getLayoutPosition()).setDNEEDLE("0");
                    }
                }
            });
            item_checkBoxyj.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    if(isChecked){
                        jychejianlist.get(holder.getLayoutPosition()).setHORN("1");
                    }else{
                        jychejianlist.get(holder.getLayoutPosition()).setHORN("0");
                    }
                }
            });

            item_beizhu.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                }

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {
                    item.setREMARK(item_beizhu.getEditableText().toString());
                }

                @Override
                public void afterTextChanged(Editable s) {

                }
            });


            item_sanlian.setText(item.getCLOTHTKTNO() == null ? "" : item.getCLOTHTKTNO());
            item_buhao.setText(item.getCLOTHNO()== null ? "" : item.getCLOTHNO());
            item_checkBoxhl.setChecked((item.getTRANLOAD()== null||Integer.parseInt(item.getTRANLOAD())==0)?false:true);
            item_checkBoxxl.setChecked((item.getGRIN()== null||Integer.parseInt(item.getGRIN())==0)?false:true);
            item_checkBoxcz.setChecked((item.getDNEEDLE()== null||Integer.parseInt(item.getDNEEDLE())==0)?false:true);
            item_checkBoxyj.setChecked((item.getHORN()== null||Integer.parseInt(item.getHORN())==0)?false:true);
            item_beizhu.setText(item.getREMARK()==null?"":item.getREMARK());
            item_checkBox.setChecked(item.isBoxcheck());
        }
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.input_dateLl:
                setDate();
                break;
            case R.id.shureBtn: {
                if (jychejianlist.size() == 0) {
                    showSimpleDialog("请先添加数据");
                    return;
                }
                savelist.clear();
                for (int i = 0; i < jychejianlist.size(); i++) {
                    if (jychejianlist.get(i).isBoxcheck()) {
                        // 添加到需要保存的列表中
                        savelist.add(jychejianlist.get(i));
                    }
                }
                if (savelist.size() == 0) {
                    showSimpleDialog("请先勾选保存的数据");
                    return;
                }
                for (JyChejianModel model : savelist) {
                    if(TextUtils.isEmpty(model.getTRANLOAD())){
                        model.setTRANLOAD("0");
                    }
                    if(TextUtils.isEmpty(model.getGRIN())){
                        model.setGRIN("0");
                    }
                    if(TextUtils.isEmpty(model.getDNEEDLE())){
                        model.setDNEEDLE("0");
                    }
                    if(TextUtils.isEmpty(model.getHORN())){
                        model.setHORN("0");
                    }
                }

                JsonArray jsonsarry = new JsonArray();
                if (type.equals("1")) {//修改
                    for (JyChejianModel model : savelist) {
                        JsonObject oneObject = new JsonObject();
                        oneObject.addProperty("PKID", model.getPKID());
                        oneObject.addProperty("DNEEDLE", model.getDNEEDLE());
                        oneObject.addProperty("HORN", model.getHORN());
                        oneObject.addProperty("TRANLOAD", model.getTRANLOAD());
                        oneObject.addProperty("GRIN", model.getGRIN());
                        oneObject.addProperty("REMARK", model.getREMARK());
                        jsonsarry.add(oneObject);
                    }
                    showWait();
                    RequestServiceImpl.jy_shurechejianlist(mMIPHandler, IServiceImpl.JY_SAVECHEJIANLIST, empID, (String) SharedPreUtil.getValue(this,
                            SharedPreUtil.YHMC, ""), type, jsonsarry.toString());
                } else {//新增
                    Gson gson = new Gson();
                    String jsonstr = gson.toJson(savelist);
                    showWait();
                    RequestServiceImpl.jy_shurechejianlist(mMIPHandler, IServiceImpl.JY_SAVECHEJIANLIST, empID, (String) SharedPreUtil.getValue(this,
                            SharedPreUtil.YHMC, ""), type, jsonstr);
                }


            }
            break;
            case R.id.deleteBtn: {
                if (jychejianlist.size() == 0) {
                    showSimpleDialog("请先添加数据");
                    return;
                }
                deletelist.clear();
                for (int i = 0; i < jychejianlist.size(); i++) {
                    if (jychejianlist.get(i).isBoxcheck()) {
                        // 添加到需要保存的列表中
                        deletelist.add(jychejianlist.get(i));
                    }
                }
                if (deletelist.size() == 0) {
                    showSimpleDialog("请先勾选删除的数据");
                    return;
                }
                if (type.equals("1")) {//查询出来的
                    String pids = "";
                    for (JyChejianModel model : deletelist) {
                        pids = pids + model.getPKID() + ",";
                    }
                    showWait();
                    RequestServiceImpl.jy_deletechejianlist(mMIPHandler, IServiceImpl.JY_DELETECHEJIANLIST, pids.substring(0, pids.length() - 1));

                } else {
                    for (int i = 0; i < jychejianlist.size(); i++) {
                        for (int j = 0; j < deletelist.size(); j++) {
                            if (jychejianlist.get(i).getUuid() == deletelist.get(j).getUuid()) {
                                jychejianlist.remove(i);
                            }
                        }
                    }
                    quickAdapter.notifyDataSetChanged();
                    checkListview();
                }
            }
            break;
            case R.id.queryBtn: {

                querylist(mJobDate, empID, editbizno.getEditableText().toString().trim());
            }
            break;
        }
    }

    public void querylist(String JobDate, String YHBH, String CLOTHTKTNO) {//根据条件查询
        showWait();
        RequestServiceImpl.jy_querychejian(mMIPHandler, IServiceImpl.JY_QUERYCHEJIAN, JobDate, YHBH, CLOTHTKTNO);
    }

    public void querysanlian(String CLOTHTKTNO) {
        showWait();
        RequestServiceImpl.jy_querysanlianchejian(mMIPHandler, IServiceImpl.JY_QUERYCHEJIANSANLIAN, CLOTHTKTNO);
    }

    @Override
    public void onPostHandle(int requestType, Object objBody, boolean error) throws Exception {
        stopWait();
        String msg = "";
        String opt = "";
            switch (requestType) {
                case IServiceImpl.JY_QUERYCHEJIAN://根据条件查询
                    try {
                        JSONObject jsonObj = new JSONObject((String) objBody);
                        msg = jsonObj.optString("MSG_INFO");
                        opt = jsonObj.optString("OPT_FLAG");
                        if ("SUCCESS".equals(opt)) {
                            JSONArray dataarray = jsonObj.optJSONArray("DATA");
                            if (dataarray != null&&dataarray.length()>0) {
                                jychejianlist.clear();
                                for (int i = 0; i < dataarray.length(); i++) {
                                    JyChejianModel zhizaoModel = ParseUtils.parse(dataarray.getJSONObject(i).toString(), JyChejianModel.class);
                                    zhizaoModel.setBoxcheck(false);
                                    zhizaoModel.setUuid(MIP_SystemUtils.getUUID());
                                    jychejianlist.add(zhizaoModel);
                                }

                            } else {
                                jychejianlist.clear();
                            }
                            quickAdapter.notifyDataSetChanged();
                            checkListview();
                            type = "1";//修改
                        } else {
                            if (TextUtils.isEmpty(msg)) {
                                showSimpleDialog("查询出错");
                            } else {
                                showSimpleDialog(msg);
                            }

                        }

                    }catch (Exception e){
                    }
                    break;
                case IServiceImpl.JY_QUERYCHEJIANSANLIAN://三联单号查询
                    try {
                        JSONObject jsonObj = new JSONObject((String) objBody);
                        msg = jsonObj.optString("MSG_INFO");
                        opt = jsonObj.optString("OPT_FLAG");
                        if ("SUCCESS".equals(opt)) {
                            JSONArray dataarray = jsonObj.optJSONArray("DATA");
                            if (dataarray != null&&dataarray.length()>0) {
                                jychejianlist.clear();
                                for (int i = 0; i < dataarray.length(); i++) {
                                    JyChejianModel zhizaoModel = ParseUtils.parse(dataarray.getJSONObject(i).toString(), JyChejianModel.class);
                                    zhizaoModel.setBoxcheck(true);
                                    zhizaoModel.setUuid(MIP_SystemUtils.getUUID());
                                    jychejianlist.add(zhizaoModel);
                                }

                            } else {
                                jychejianlist.clear();
                            }
                            quickAdapter.notifyDataSetChanged();
                            checkListview();
                            type="0";//新增
                        } else {
                            if (TextUtils.isEmpty(msg)) {
                                showSimpleDialog("查询三联单出错");
                            } else {
                                showSimpleDialog(msg);
                            }

                        }

                    }catch (Exception e){
                    }
                    break;
                case IServiceImpl.JY_SAVECHEJIANLIST://保存
                    try {
                        JSONObject jsonObj = new JSONObject((String) objBody);
                        msg = jsonObj.optString("MSG_INFO");
                        opt = jsonObj.optString("OPT_FLAG");
                        if ("SUCCESS".equals(opt)) {
                            showSimpleDialog("您已成功保存"+savelist.size()+"条数据！");
                            if(type.equals("0")) {//新增
                                jychejianlist.clear();
                                quickAdapter.notifyDataSetChanged();
                                checkListview();
                                editbizno.setText("");
                            }
                        } else {
                            if (TextUtils.isEmpty(msg)) {
                                showSimpleDialog("保存出错");
                            } else {
                                showSimpleDialog(msg);
                            }

                        }

                    }catch (Exception e){
                    }
                    break;
                case IServiceImpl.JY_DELETECHEJIANLIST://删除
                    try {
                        JSONObject jsonObj = new JSONObject((String) objBody);
                        msg = jsonObj.optString("MSG_INFO");
                        opt = jsonObj.optString("OPT_FLAG");
                        if ("SUCCESS".equals(opt)) {
                            for(int i=0;i<jychejianlist.size();i++){
                                for(int j=0;j<deletelist.size();j++){
                                    if(jychejianlist.get(i).getUuid()==deletelist.get(j).getUuid()){
                                        jychejianlist.remove(i);
                                    }
                                }
                            }
                            quickAdapter.notifyDataSetChanged();
                            checkListview();
                            showSimpleDialog("您已成功删除"+deletelist.size()+"条数据！");
                        } else {
                            if (TextUtils.isEmpty(msg)) {
                                showSimpleDialog("删除出错");
                            } else {
                                showSimpleDialog(msg);
                            }

                        }

                    }catch (Exception e){
                    }
                    break;
                case IServiceImpl.JY_GETTIME://获取时间
                    try {
                        if (!TextUtils.isEmpty((String) objBody)) {
                            mJobDate=dateFormat_EN.format(dateFormat_EN.parse(objBody.toString()));
                            input_dateTv.setText(dateFormat_CHINA.format(dateFormat_EN.parse(objBody.toString())));
                        }

                    }catch (Exception e){
                    }
                    break;


            }
    }

    private void showSimpleDialog(String message) {
        SimpleDialog.Companion.newInstance(message).show(getSupportFragmentManager(), "DialogTip");
    }
    /**
     * 检查listview是否为空
     */
    private void checkListview() {
        if (jychejianlist.size() > 0) {
            recylistview.setVisibility(View.VISIBLE);
        } else {
            recylistview.setVisibility(View.GONE);
        }
    }


    /**
     * 设置日期
     */
    private void setDate() {
        String[] strNow = mJobDate.toString().split("-");
        DatePickerDialog datePickerDialog = new DatePickerDialog(this, mOnDateSetListenernew, Integer.parseInt(strNow[0]), Integer.parseInt(strNow[1])-1, Integer.parseInt(strNow[2]));
        datePickerDialog.show();
    }

    /**
     * 日期选择监听器
     */
    DatePickerDialog.OnDateSetListener mOnDateSetListenernew = new DatePickerDialog.OnDateSetListener() {
        @Override
        public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
            String date = year + "年" + String.format("%02d", month + 1) + "月" + String.format("%02d", dayOfMonth)+"日";
            input_dateTv.setText(date);
            mJobDate = year + "-" + String.format("%02d", month + 1) + "-" + String.format("%02d", dayOfMonth);

        }
    };
}